/*
    Copyright 2009 Barnet Wagman

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

package ot.s3;

import java.util.*;

/** An {@link ErrorHandler} that retries forever.  The time between
 *  retries increases until a max is reached.
 *
 * @author Barnet Wagman
 */
public class RetryForeverErrorHandler implements ErrorHandler {
    
    public static long MAX_RETRY_INTERVAL = 1000L * 60L;
    
    long retryIntervalMillis;
    List<Throwable> throwables;
    int nThrowables;
    
    public RetryForeverErrorHandler() {
        nThrowables = 0;
        retryIntervalMillis = ConstantsOtS3.RETRY_INTERVAL_MILLIS_DEFAULT;
    }      
    
        /** Only the first and last throwables are stored in the throwable list.
         * 
         * @param x
         * @return
         */
    public Action add(Throwable x) {
        
        ++nThrowables;
        if ( throwables == null ) throwables = new ArrayList<Throwable>();
        
        if ( throwables.size() == 0 ) throwables.add(x);       
        else if ( throwables.size() == 1 ) throwables.add(x);
        else throwables.set(1,x);
        
        if ( retryIntervalMillis >= MAX_RETRY_INTERVAL )
            System.out.println("Retrying on " + x);
                
        UtilOtS3.nap(retryIntervalMillis);
        retryIntervalMillis += ConstantsOtS3.RETRY_INTERVAL_MILLIS_DEFAULT;
        
        return(Action.retry);        
    }
    
        /** Gets the first and last throwables.
         * 
         * @return
         */
    public List<Throwable> getThrowables() { return(throwables); } 
    
    public ErrorHandler cloneErrorHandler() {
        return( new RetryForeverErrorHandler() );
    }
}
